#
#    Copyright 2006 Andrew Wilkinson <aw@cs.york.ac.uk>.
#
#    This file is part of PyScobble (http://lastfm.indiegigs.co.uk/pyscrobble)
#
#    PyScobble is free software; you can redistribute it and/or modify
#    it under the terms of the GNU Lesser General Public License as published by
#    the Free Software Foundation; either version 2.1 of the License, or
#    (at your option) any later version.
#
#    PyScobble is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public License
#    along with PyScobble; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

import datetime
import threading

from scrobble import Artist, Track
from scrobble.user import User
from scrobble.database import getScrobbleCache, addToScrobbleCache

lock = threading.Semaphore()
caching = False

sockets = {}

def scrobbleTrack(user, track, time=None):
    assert isinstance(user, User), user
    assert isinstance(track, Track), track
    if user.passwd is None:
        raise ValueError, "To scrobble tracks the user's password is required"

    if time is None:
        time = datetime.datetime.now()

    lock.acquire()
    try:
        if caching:
            addToScrobbleCache(user, track, time)
            return
        else:
            s = getConnection(user)
            #s.request(
            print "POST", "/", "user=%s&s=%s&a[0]=%s&t[0]=%s&b[0]=%s&m[0]=%s&l[0]=%i&i[0]=%s" % (
                                    user.username,
                                    s.md5response,
                                    track.artist.name,
                                    track.name,
                                    track.albumname or "",
                                    track.mbid or "",
                                    track.length or "",
                                    time.strftime("%Y-%m-%d %H:%M:%S"))
            #         )
    finally:
        lock.release()

def getConnection(user):
    return
